{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "functioning-hurricane",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from sklearn.metrics import roc_curve\n",
    "from sklearn.metrics import auc"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "metropolitan-adjustment",
   "metadata": {},
   "outputs": [],
   "source": [
    "def auc_calculate(labels,preds,n_bins=100):\n",
    "    postive_len = sum(labels)\n",
    "    negative_len = len(labels) - postive_len\n",
    "    total_case = postive_len * negative_len\n",
    "    pos_histogram = [0 for _ in range(n_bins)]\n",
    "    neg_histogram = [0 for _ in range(n_bins)]\n",
    "    bin_width = 1.0 / n_bins\n",
    "    for i in range(len(labels)):\n",
    "        nth_bin = int(preds[i]/bin_width)\n",
    "        if labels[i]==1:\n",
    "            pos_histogram[nth_bin] += 1\n",
    "        else:\n",
    "            neg_histogram[nth_bin] += 1\n",
    "    accumulated_neg = 0\n",
    "    satisfied_pair = 0\n",
    "    for i in range(n_bins):\n",
    "        satisfied_pair += (pos_histogram[i]*accumulated_neg + pos_histogram[i]*neg_histogram[i]*0.5)\n",
    "        accumulated_neg += neg_histogram[i]\n",
    "\n",
    "    return satisfied_pair / float(total_case)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "conservative-market",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-----sklearn: 0.7708333333333334\n"
     ]
    }
   ],
   "source": [
    "y = np.array([1,1,1,1,0,0,0,0,0,0])\n",
    "pred = np.array([0.6, 0.8, 0.2, 0.9,0.1,0.2,0.2,0.3,0.6,0.7])\n",
    "\n",
    "\n",
    "fpr, tpr, thresholds = roc_curve(y, pred, pos_label=1)\n",
    "print(\"-----sklearn:\",auc(fpr, tpr))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "portable-spiritual",
   "metadata": {},
   "outputs": [],
   "source": [
    "#问答题"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "enhanced-assignment",
   "metadata": {},
   "outputs": [],
   "source": [
    "a：\n",
    "        韩梅梅采用OneHotEncoder独热编码，而李雷采用的是 LabelEncoder标签编码（即用某一个数字代表一种类型，如1代表一线城市，2代表二线城市，3代表三线城市）。如果模型损失函数对变量的数值大小是敏感的，如SVM、LR、GLM等，为模型A；如果模型损失函数对变量数据大小不敏感，数值的存在意义是为了排序，如各种树模型，则为模型B。显然该题用的LR模型对变量数值大小是敏感的，所以韩梅梅的编码方式更合适。\n",
    "b：\n",
    "       beta为机器学习模型中的截距，如果设置为1，与事实相比过大，可能需要模型训练更长时间。所以 韩梅梅更好，能在短时间找到最优的模型参数。\n",
    "c：\n",
    "      在训练样本中拟合的很好，但是在测试样本中效果比较差，属于过拟合问题。该损失函数使用的是经验风险最小化，不是结构风险最小化，泛化能力差，容易过拟合。（结构风险=经验风险+置信风险，置信风险是一个减函数，整个公示反映了经验风险和真实误差的差距上界，表征了根据经验风险最小化原则得到的模型的泛化能力。称为泛化误差上界。）\n",
    "d：\n",
    "    AUC最大的应用应该就是点击率预估（CTR）的离线评估。其计算过程如下：\n",
    "    得到结果数据，数据结构为：（输出概率，标签真值）\n",
    "    对结果数据按输出概率进行分组，得到（输出概率，该输出概率下真实正样本数，该输出概率下真实  负样本数）。这样做的好处是方便后面的分组统计、阈值划分统计等\n",
    "    对结果数据按输出概率进行从大到小排序\n",
    "    从大到小，把每一个输出概率作为分类阈值，统计该分类阈值下的TPR和FPR\n",
    "    微元法计算ROC曲线面积、绘制ROC曲线\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
